import { login, logout, navMenu } from '@/api/user/login'
import { setToken } from '@/lib/util'

const state = {
  userName: 'wangfengxi'
}

const getters = {
  firstUserName: (state) => {
    return state.userName.substr(0, 1)
  }
}

const mutations = {
  SET_USER_NAME (state, params) {
    state.userName = params
  }
}

const actions = {
  /**
   * commit提交
   * state 指本实例中的 state
   * rootState 指根实例中的state
   * @param commit
   * @param state
   * @param rootState
   */
  updateUserName ({ commit, state, rootState, dispatch }) {
    const name = rootState.appName + '-' + state.userName
    dispatch('updateName', name)
  },
  updateName ({ commit }, name) {
    commit('SET_USER_NAME', name)
  },
  login ({ commit }, params) {
    return new Promise((resolve, reject) => {
      login(params).then(res => {
        console.log(res)
        let data = res.data
        if (data.code === 0 && data.token) {
          setToken(data.token)
          resolve()
        } else {
          reject(new Error('用户名密码错误'))
        }
      }).catch(error => {
        reject(error)
      })
    })
  },
  handleLogout ({ state, commit }) {
    return new Promise((resolve, reject) => {
      logout().then(res => {
        let data = res.data
        console.log(data)
        if (data.code === 0) {
          setToken('')
        }
        resolve()
      }).catch(error => {
        setToken('')
        reject(error)
      })
    })
  },
  navMenu ({ commit }, token) {
    return new Promise((resolve, reject) => {
      navMenu().then(res => {
        console.log('navMenu star', res.data.data.rules)
        resolve(res.data.data.rules)
      }).catch(error => {
        console.log('navMenu error', error)
        reject(error)
      })
    })
  }
}

export default {
  // namespaced 表示使用命名空间
  // namespaced: true,
  getters,
  state,
  mutations,
  actions
}
